<template>
  <el-form class="auth-form" ref="formRef" :model="form" label-width="80px" size="default" status-icon>
    <el-form-item v-for="item of formItems" :key="item.prop" v-bind="item">
      <component style="width: 100%" :is="item.tag" v-bind="item.bind" v-model="form[item.prop]" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit(formRef)">登录</el-button>
      <el-button @click="onReset(formRef)">清空</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref(null)
const form = ref({})
const formItems = ref([
  {
    prop: 'loginName',
    label: '账号',
    rules: [{ required: true, message: '请填写账号', trigger: 'blur' }],
    tag: 'el-input',
    bind: {
      clearable: true,
      placeholder: '请填写账号'
    }
  },
  {
    prop: 'password',
    label: '密码',
    rules: [{ required: true, message: '请填写密码', trigger: 'blur' }],
    tag: 'el-input',
    bind: {
      type: 'password',
      clearable: true,
      placeholder: '请填写密码'
    }
  },
  {
    prop: 'role',
    label: '角色',
    rules: [{ required: true, message: '请选择角色', trigger: 'blur' }],
    tag: 'el-select-v2',
    bind: {
      clearable: true,
      filterable: true,
      allowCreate: true,
      reserveKeyword: false,
      placeholder: '请选择角色',
      options: [
        { label: '管理员', value: 'admin' },
        { label: '运维', value: 'operate' },
        { label: '开发', value: 'develop' }
      ]
    }
  }
])
const onSubmit = async (r) => {
  if (!r) {
    return false
  }
  await r.validate((valid) => {
    if (valid) {
      // 调用登录接口，将token存储到本地
      // 通过token获取用户信息，存储到window
      // 通过token获取菜单信息，存储到window
      // 下方模拟存储token用于体验
      const token = 'template_token'
      localStorage.setItem(import.meta.env.VITE_APP_TOKEN_NAME, token)
      router.push('/')
    }
  })
}
const onReset = async (r) => {
  if (!r) {
    return false
  }
  await r.resetFields()
}
</script>

<style scoped>
.auth-form {
  width: 320px;
}
</style>
